﻿using System;
using System.Collections.Generic;
using System.IO;

namespace Game.Networking.Client {
	class ScriptHolder {
		string                              folderPath;
		private List<Tuple<String, String>> files = new List<Tuple<string, string>>();

		private string getFullpath(string fileName) {
			return folderPath + fileName + ".cs";
		}

		public List<Tuple<string, string>> GetFiles() {
			return GetFiles(folderPath);
		}

		public bool TryGetValue(string fileName, out string codeFile) {
			codeFile = File.ReadAllText(getFullpath(fileName));
			return true;
		}

		public bool ContainsKey(string fileName) {
			return File.Exists(getFullpath(fileName));
		}

		public string this[string fileName] {
			get { throw new NotImplementedException(); }
			set { File.WriteAllText(getFullpath(fileName), value); }
		}

		public void Add(string fileName, string contents) {
			File.WriteAllText(getFullpath(fileName), contents);
		}

		public void SetPath(string path) {
			folderPath = path;
		}

		public void Init(string path) {
			Directory.CreateDirectory(path);
			files = GetFiles(path);
			folderPath = path;
		}

		public List<Tuple<string, string>> GetFiles(string path) {
			//TODO validate read/write rights
			var directoryInfo = new DirectoryInfo(path);
			var files = directoryInfo.GetFiles("*.cs");
			List<Tuple<string, string>> scriptfiles = new List<Tuple<string, string>>();
			foreach ( var file in files ) {
				Tuple<string, string> scriptfile =
					new Tuple<string, string>(Path.GetFileNameWithoutExtension(file.Name),
						File.ReadAllText(file.FullName));
				scriptfiles.Add(scriptfile);
			}

			return scriptfiles;
		}

		public List<string> GetFileNames() {
			var directoryInfo = new DirectoryInfo(folderPath);
			var files = directoryInfo.GetFiles("*.cs");
			List<string> filenames = new List<string>();
			foreach ( var fileInfo in files ) {
				filenames.Add(Path.GetFileNameWithoutExtension(fileInfo.Name));
			}

			return filenames;
		}

		public void Remove(string filename) {
			File.Delete(getFullpath(filename));
		}
	}
}